﻿
namespace DoNet.Helper
{
    /// <summary>
    /// HTTP请求帮助类
    /// </summary>
    public class HttpHelper
    {
        private static readonly HttpClient client = new HttpClient();

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut">默认值是 100 秒</param>
        /// <returns></returns>
        public static ReturnData HttpGet(string url, int timeOut = 100)
        {
            bool success = false;
            string message = string.Empty;
            string data = string.Empty;
            try
            {
                client.Timeout = TimeSpan.FromSeconds(timeOut * 1000);
                success = true;
                data = client.GetStringAsync(url).Result;
            }
            catch (Exception e)
            {
                // 处理其他异常
                //Console.WriteLine("Exception: " + e.Message);
                message = e.Message;
            }
            return new ReturnData()
            {
                success = success,
                message = message,
                data = data
            };
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="contentType">用来指定消息体的格式的，application/x-www-form-urlencoded、application/json等</param>
        /// <param name="timeOut">默认值是 100 秒</param>
        /// <returns></returns>
        public static ReturnData HttpPost(string url, string param, string contentType = "", int timeOut = 100)
        {
            bool success = false;
            string message = string.Empty;
            string data = string.Empty;
            try
            {
                client.Timeout = TimeSpan.FromSeconds(timeOut * 1000);
                if (!string.IsNullOrWhiteSpace(contentType))
                {
                    client.DefaultRequestHeaders.Add("Content-Type", contentType);
                }
                StringContent stringContent = new StringContent(param);//创建请求内容 并指定内容的编码格式和content-type

                success = true;
                data = client.PostAsync(url, stringContent).Result.Content.ReadAsStringAsync().Result;
            }
            catch (Exception e)
            {
                // 处理其他异常
                //Console.WriteLine("Exception: " + e.Message);
                message = e.Message;
            }
            return new ReturnData()
            {
                success = success,
                message = message,
                data = data
            };
        }

        /// <summary>
        /// POST上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramDic">其他参数列表</param>
        /// <param name="name">url端接收文件参数名，如file等</param>
        /// <param name="fileDic">上传文件的列表。 （文件名称（含后缀），文件bytes）</param>
        /// <param name="timeOut">默认值是 100 秒</param>
        /// <returns></returns>
        public static ReturnData HttpPostFile(string url, Dictionary<string, string> paramDic, string name, Dictionary<string, byte[]> fileDic, int timeOut = 100)
        {
            bool success = false;
            string message = string.Empty;
            string data = string.Empty;
            try
            {
                client.Timeout = TimeSpan.FromSeconds(timeOut * 1000);
                using (var multipartFormData = new MultipartFormDataContent())
                {
                    foreach (var param in paramDic)
                    {
                        multipartFormData.Add(new StringContent(param.Value), param.Key, "formdata");
                    }
                    foreach (var file in fileDic)
                    {
                        multipartFormData.Add(new ByteArrayContent(file.Value), name, file.Key);
                    }

                    success = true;
                    data = client.PostAsync(url, multipartFormData).Result.EnsureSuccessStatusCode().IsSuccessStatusCode.ToString();
                }
            }
            catch (Exception e)
            {
                // 处理其他异常
                //Console.WriteLine("Exception: " + e.Message);
                message = e.Message;
            }
            return new ReturnData()
            {
                success = success,
                message = message,
                data = data
            };
        }
    }

    public class ReturnData
    {
        /// <summary>
        /// 是否请求成功
        /// </summary>
        public bool success { set; get; }
        /// <summary>
        /// 失败时的错误内容
        /// </summary>
        public string message { set; get; } = string.Empty;
        /// <summary>
        /// 成功时返回的数据
        /// </summary>
        public string data { set; get; } = string.Empty;
    }
}
